<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="handleSearchList"
          size="s米糕"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch"
          size="s米糕"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="s米糕"
          label-width="140px"
        >
          <el-form-item label="派单日期：">
            <el-date-picker
              v-model="searchAskForLeave"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              clearable
            >
              >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <!-- <el-button
          size="mini"
          class="btn-add"
          @click="handleAdd()"
          style="margin-left: 20px"
          >添加</el-button
        > -->
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column label="派单日期" align="center">
          <template slot-scope="scope">{{
            formatDate(new Date(scope.row.date), "yyyy/MM/dd")
          }}</template>
        </el-table-column>
        <el-table-column label="派单数量" align="center">
          <template slot-scope="scope">{{ scope.row.num }}</template>
        </el-table-column>

    
        <el-table-column label="派单人" align="center">
          <template slot-scope="scope">
            {{ scope.row.adminName }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <!-- <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.$index, scope.row)"
              >
                编辑
              </el-button> -->

            <el-button
              size="mini"
              type="text"
              @click="handleShowList(scope.$index, scope.row)"
              >查看
            </el-button>

            <!--   -->

            <el-dropdown  @command='(param) => handleCommand(param, scope.$index, scope.row)'>
              <span class="el-dropdown-link">
                阅览<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="frontRead" >导出前道</el-dropdown-item>
                <el-dropdown-item command="frontReadPlus" >导出前道+</el-dropdown-item>
                <el-dropdown-item command="afterRead">导出后道</el-dropdown-item>
              </el-dropdown-menu>
          </el-dropdown>


            <el-button
              size="mini"
              type="text"
              @click="handleExport(scope.$index, scope.row)"
              >导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div
      class="pagination-container"
      style="
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-bottom: 20px;
      "
    >
      <!-- <el-pagination
          background
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="listQuery.pageNum"
          :page-size="historyParams.pageSize"
          :total="historyParams.total"
        >
        </el-pagination> -->
    </div>
    <el-dialog
      class="my-dialog"
      :title="
        '派单日期：' +
        formatDate(new Date(showParams.createTime * 1000), 'yyyy/MM/dd')
      "
      :visible.sync="dialogVisible"
      width="70%"
      destroy-on-close
      @closed="closed"
    >
      <el-table
        ref="productTable"
        :data="showList"
        style="width: 100%"
        v-loading="showListLoading"
        :default-sort="{ prop: 'time', order: 'ascending' }"
        border
      >
        <el-table-column label="公司名称" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.companyName }}</p>
          </template>
        </el-table-column>
        <el-table-column
          label="时间"
          align="center"
          prop="time"
          sortable
          :filters="[
            { text: '上午', value: 'AM' },
            { text: '下午', value: 'PM' },
          ]"
          :filter-method="filterMethod"
        >
          <template slot-scope="scope">
            <p>
              {{ scope.row.time }}
            </p>
          </template>
        </el-table-column>

        <el-table-column label="企业编号" align="center">
          <template slot-scope="scope">{{ scope.row.companyId }}</template>
        </el-table-column>

        <el-table-column label="出单人" align="center">
          <template slot-scope="scope">{{ scope.row.seller }}</template>
        </el-table-column>


        <el-table-column label="地址" width="300" align="left">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <div>{{ scope.row.companyAddress }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="员工" align="center">
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <el-tag
                type="warning"
                style="margin-left: 5px; margin-right: 10px"
                :style="{
                  visibility:
                    scope.row.assignPersonnel === 1 ? 'visible' : 'hidden',
                }"
                >指派</el-tag
              >
              <div>
                {{ scope.row.userName }}
              </div>
              <div></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="行程时间"
          align="center"
          prop="duration"
          sortable
        >
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <i
                class="el-icon-truck"
                style="font-size: 18px; margin-left: 20px; margin-right: 10px"
              ></i>
              <div>{{ convertTime(scope.row.duration) }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-pagination
          background
          @current-change="handleCurrentChangeShowList"
          layout="total,prev, pager, next,jumper"
          :page-size="showPageSize"
          :total="showTotal"
          :currentPage.sync="showParams.pageNum"
        >
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  dispatchHistory,
  dispatchHistoryList,
  dispatchHistorySearch,
} from "../../../api/dispatch";
import { formatDate } from "@/utils/date";
import { maxNum, minNum } from "../../../utils/max";
import { fileExport, fileReadExport } from "@/utils/export";
import { getStartAndEndTime } from '../../../utils/time';
const defaultListQuery = {
  pageNum: 1,
  startTime: null,
  endTime: null,
};

const statusOptions = [
  {
    label: "正常",
    value: 0,
  },
  {
    label: "请假",
    value: 1,
  },
];
const statusOptionss = ["正常", "请假"];

const postOptions = ["前道", "后道"];

export default {
  name: "dispatch-history",
  data() {
    return {
      readStatus: false,
      statusOptionss,
      listQuery: Object.assign({}, defaultListQuery),
      list: [],
      listLoading: false,
      isEdit: false,
      statusOptions,
      postOptions,
      askForLeave: null,
      searchAskForLeave: null,
      formatDate,
      dialogVisible: false,
      historyParams: {
        pageNum: 1,
        pageSize: null,
        total: 0,
      },
      showParams: {
        // 页码
        pageNum: 1,
        // 派单时间
        createTime: null,
        // 管理员 编号
        adminId: null,
        // 最后序号id
        lastId: 0,
      },
      showPageSize: null,
      showTotal: 0,
      showList: [],
      showListLoading: false,
      allList: [],
      exportParams: {
        pageNum: 1,
        createTime: null,
        adminId: null,
        lastId: 0,
      },
    };
  },
  created() {
    this.getList();
  },

 

  methods: {
    filterMethod(value, row) {
      let t = row.time.split(":")[0] * 1 < 12 ? "AM" : "PM";
      return t === value;
    },

    handleCommand(param, index, row) {
      console.log("handle", param);
      this[param](index, row);
    },

    /**
     * 阅览
     */
    frontRead(index, row) {
      console.log("row", row);
      this.commonExport(index, row, fileReadExport, 0);
    },

    /**
     * 导出前道+
     */
    frontReadPlus(index, row) {
      this.commonExport(index, row, fileReadExport, 2);
    },

    /**
     * 后道
     */
    afterRead(index, row) {
      this.commonExport(index, row, fileReadExport, 1);
    },

    /**
     * 公共导出
     */
    async commonExport(index, row, func, type) {
      const { date, adminId } = row;
      this.exportParams.createTime = new Date(date).getTime() / 1000;
      this.exportParams.adminId = adminId;
      this.exportParams.pageNum = 1;
      this.exportParams.lastId = 0;
      //获取所有数据

      await this.getAllList(func, type);
    },


    // 导出函数
    async handleExport(index, row) {
     
      // 获取所有数据
      this.commonExport(index, row, fileExport);
    },

    async getAllList(func, type) {
      return await dispatchHistoryList(this.exportParams).then((res) => {
        if (this.exportParams.pageNum == 1) {
          this.allList = [];
        }
        this.allList = this.allList.concat(res.data.data);
        console.log("this.allList", this.allList);
        this.exportParams.pageSize = res.data.pageSize;
        this.exportParams.total = res.data.total;
        this.exportParams.lastId = maxNum(res.data.data, "id");
        const totalPage = Math.ceil(res.data.total / res.data.pageSize);
        if (this.exportParams.pageNum < totalPage) {
          this.exportParams.pageNum++;
          // 继续获取下一页数据
          this.getAllList(func, type);
        } else {
          func(this.allList, type);
        }
      });
    },

    handleShowList(index, row) {
      this.showParams.createTime = new Date(row.date).getTime() / 1000;
      this.showParams.adminId = row.adminId;
      this.dialogVisible = true;
      this.showParams.pageNum = 1;
      this.getShowList();
    },
    getShowList() {
      this.showListLoading = true;
      dispatchHistoryList(this.showParams).then((res) => {
        this.showList = res.data.data;
        this.showPageSize = res.data.pageSize;
        this.showTotal = res.data.total;
        this.showListLoading = false;
      });
    },
    handleCurrentChangeShowList(val) {
      if (val === 1) {
        this.showParams.lastId = 0;
        this.getShowList();
      }
    },
    // 弹窗关闭回调
    closed() {
      // this.$refs.adminForm.clearValidate();
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.handleSearchList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
    
      let time = getStartAndEndTime(this.searchAskForLeave);

      if (0 != time.length) {
        this.listQuery.startTime = time[0];

        this.listQuery.endTime = time[1];
      }

      this.listLoading = true;
      this.searchHistory();
    },

    // 搜索
    searchHistory() {
      dispatchHistorySearch(this.listQuery).then((res) => {
        this.historyParams.pageSize = res.data.pageSize;
        this.list = this.list.concat(res.data.data);
        if (res.data.data.length === res.data.pageSize) {
          this.listQuery.pageNum++;
          this.searchHistory();
        } else {
          this.listLoading = false;
        }
      });
    },

    getList() {
      this.listLoading = true;
      this.getHistory();
    },

    // 获取数据
    getHistory() {
      dispatchHistory({ pageNum: this.historyParams.pageNum }).then((res) => {
        this.historyParams.pageSize = res.data.pageSize;
        this.list = this.list.concat(res.data.data);
        if (res.data.data.length === res.data.pageSize) {
          this.historyParams.pageNum++;
          this.getHistory();
        } else {

          this.list.sort((f,s) => new Date(s.date) - new Date(f.date))

          this.listLoading = false;
        }
      });
    },

    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      if (this.searchAskForLeave) {
        this.handleSearchList();
      } else {
        this.getList();
      }
    },
  },

  watch: {
    "showParams.pageNum": {
      handler(newVal, oldVal) {
        if (newVal === 1) {
          this.showParams.lastId = 0;
          return false;
        } else {
          if (newVal > oldVal && newVal === oldVal + 1) {
            this.showParams.lastId = maxNum(this.showList, "id");
          } else if (newVal > oldVal && newVal !== oldVal + 1) {
            let num = 0;
            num =
              maxNum(this.showList, "id") +
              (newVal - oldVal - 1) * (this.showPageSize || 30);
            this.showParams.lastId = num;
          } else if (newVal < oldVal) {
            let num1 = 0;
            num1 =
              minNum(this.showList, "id") -
              1 -
              (oldVal - newVal) * (this.showPageSize || 30);
            this.showParams.lastId = num1;
          }
        }
        this.getShowList();
      },
      deep: true,
    },
  },
  computed: {
    tooltipShow() {
      return (row) => {
        let start = new Date(row.leaveStart * 1000).getTime();
        let end = new Date(row.leaveEnd * 1000).getTime();
        let now = new Date().getTime();
        if (now < end) {
          return true;
        } else {
          return false;
        }
      };
    },
    formatDateTime() {
      return (time) => {
        if (time == null || time === "") {
          return "N/A";
        }
        let date = new Date(time);
        return formatDate(date, "yyyy/MM/dd hh:mm:ss");
      };
    },
    ...mapState(["areas"]),
    areaComputed() {
      return (value) => {
        if (this.$store.state.areas) {
          const item = this.$store.state.areas.find(
            (item) => item.id === value
          );
          return item ? item.name : "";
        }
        return this.$store.state.areas;
      };
    },
    // 时间换算
    convertTime() {
      return (seconds) => {
        if (!seconds) return "";
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);

        if (hours > 0) {
          return hours + "h " + minutes + "min";
        }

        return minutes + " min";
      };
    },
  },
};
</script>
  <style scoped>
.my-dialog :deep(.el-dialog) {
  min-width: 650px;
  max-width: 100%;
}
.table-container {
  display: flex;
  flex-direction: column;
  flex: auto;
  background-color: red;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    margin-left: 5px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
    
    
    